<?php

declare(strict_types=1);

namespace So\App\Controller\Backend;

use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use So\Annotation\Auth;
use Hyperf\HttpServer\Annotation\GetMapping;
use So\Annotation\Validation;
use So\Controller\Backend;
use So\Annotation\Controller;
use So\Library\Auth as AuthLib;
use Hyperf\Di\Annotation\Inject;
use So\Annotation\AdminLog;
use So\Library\Upload;
use So\Annotation\Model;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\DeleteMapping;

/**
 * @Controller(prefix="file")
 * @Auth()
 * @AdminLog()
 */
class FileController extends Backend
{
    /**
     * Auth类
     * @Inject
     * @var AuthLib
     */
    protected $auth;

    /**
     * @Inject
     * @var Upload
     */
    protected $upload;

    /**
     * 上传文件
     * @PostMapping("upload")
     */
    public function upload()
    {
        $upload = $this->upload->pull($this->request->file("file"), ['admin_id' => $this->auth->id]);
        if ($upload) {
            return $this->success('上传成功', $upload['url']);
        }
        return $this->error($this->upload->getError());
    }

    /**
     * @GetMapping("read")
     * @Model
     */
    public function read($model): ResponseInterface
    {
        return parent::read($model);
    }

    protected function _read_model(&$model)
    {
        !$this->auth->isSuperAdmin($this->auth->id) && $model->where('admin_id', '=', $this->auth->id);
    }

    /**
     * @PutMapping("update")
     * @Validation
     * @Model
     */
    public function update($data, $model): ResponseInterface
    {
        return parent::update($data, $model);
    }

    /**
     * @DeleteMapping("delete")
     * @Model
     */
    public function delete($data, $model): ResponseInterface
    {
        return parent::delete($data, $model);
    }

    protected function _delete($ids, $model)
    {
        if (!$this->auth->isSuperAdmin($this->auth->id)){
            foreach ($ids as $k => $v){
                $res = $model::query()->where('admin_id','=',$this->auth->id)->where('id','=',$v)->first();
                if (!$res) unset($ids[$k]);
            }
        }
        foreach ($ids as $v) {
            $res = $model::query()->find($v);
            if ($res) {
                $this->upload->delete($res['type'], $res['path']);
            }
        }
        return $ids;
    }

}